package view;

import java.util.LinkedList;
import java.util.List;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.util.AttributeSet;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;

import com.devgroupvn.dota.NEWSAdapter;
import com.devgroupvn.dota.NewsArchive;
import com.devgroupvn.dota.Post;
import com.devgroupvn.dota.WebViewNews;

public class NewsPage extends LinearLayout
{
	private NEWSAdapter adapterNEWS;
	Context mContext;
	ListView mListView;
	Activity mActivity;
	ProgressDialog progressDialog;
	public static List<Post> listDataNEWS = new LinkedList<Post>();

	public NewsPage(Context context, AttributeSet attrs)
	{
		super(context, attrs);
		init();
	}

	public NewsPage(Context context, Activity _activity)
	{
		super(context);
		mContext = context;
		mActivity = _activity;
		init();
		action();
		new AsyntaskLoadNews().execute();
	}

	private void init()
	{
		mListView = new ListView(getContext());
		LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
		addView(mListView, params);
	}

	private void action()
	{
		mListView.setOnItemClickListener(new OnItemClickListener()
		{

			@Override
			public void onItemClick(AdapterView<?> a, View v, int position, long id)
			{
				String link = listDataNEWS.get(position).link;
				Intent intent = new Intent(mActivity, WebViewNews.class);
				intent.putExtra("link", link);
				mActivity.startActivity(intent);
			}

		});
	}

	public class AsyntaskLoadNews extends AsyncTask<Void, Void, Void>
	{

		@Override
		protected Void doInBackground(Void... params)
		{
			listDataNEWS = new NewsArchive().getListNew();
			return null;
		}

		@Override
		protected void onPostExecute(Void result)
		{
			if (listDataNEWS != null)
			{
				adapterNEWS = new NEWSAdapter(mActivity, listDataNEWS);
				mListView.setAdapter(adapterNEWS);
				adapterNEWS.notifyDataSetChanged();
			}
			else
			{
				new AsyntaskLoadNews().execute();
			}
			super.onPostExecute(result);
		}

		@Override
		protected void onPreExecute()
		{
			super.onPreExecute();
		}

	}

}
